from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    note_type = db.Column(db.String(10), nullable=False)  # daily/weekly/monthly
    timestamp = db.Column(db.DateTime, nullable=False)


@app.route('/')
def index():
    note_type = request.args.get('type', 'daily')
    notes = Note.query.filter_by(note_type=note_type).order_by(Note.timestamp.desc()).all()
    return render_template('index.html', notes=notes, note_type=note_type)


@app.route('/add', methods=['GET', 'POST'])
def add_note():
    if request.method == 'POST':
        content = request.form['content']
        note_type = request.form['note_type']
        timestamp = datetime.strptime(request.form['timestamp'], '%Y-%m-%d')

        new_note = Note(
            content=content,
            note_type=note_type,
            timestamp=timestamp
        )
        db.session.add(new_note)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('add.html')


@app.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit_note(id):
    note = Note.query.get_or_404(id)
    if request.method == 'POST':
        note.content = request.form['content']
        note.note_type = request.form['note_type']
        note.timestamp = datetime.strptime(request.form['timestamp'], '%Y-%m-%d')
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('edit.html', note=note)


@app.route('/delete/<int:id>')
def delete_note(id):
    note = Note.query.get_or_404(id)
    db.session.delete(note)
    db.session.commit()
    return redirect(url_for('index'))


if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)